// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {

  let station_id = event.station_id

  // collection 上的 get 方法会返回一个 Promise，因此云函数会在数据库异步取完数据后返回结果
  let stations = await db.collection('stations').where({
    _id: station_id
  }).get()

  let station = stations.data[0]
  //查询油站油价
  let _price = await db.collection('oil_prices').where({
    station_id: station._id
  }).orderBy('created_time', 'desc').limit(1).get()
  if (_price.data.length > 0) {
    station.oil_price = _price.data[0] //唯一的 一条
  }else{
    //查出本地官方油价
    let state_price = await db.collection('oil_prices').where({
      station_id: 'default'
    }).get()
    station.oil_price = state_price.data[0] //唯一的 一条
  }


  return station
}